import { NotificationState } from '../contexts/LiveNotificationContext';

// 存储键名
const STORAGE_KEY = 'dataplexus_dynamic_island_notifications';
const MAX_STORED_NOTIFICATIONS = 10; // 最大存储通知数量
const NOTIFICATION_EXPIRY_TIME = 24 * 60 * 60 * 1000; // 24小时过期时间

// 存储的通知数据结构
interface StoredNotificationData {
  notifications: NotificationState[];
  timestamp: number;
  version: string; // 用于版本兼容性检查
}

// 防抖函数
function debounce<T extends (...args: any[]) => void>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout | null = null;
  
  return (...args: Parameters<T>) => {
    if (timeout) {
      clearTimeout(timeout);
    }
    
    timeout = setTimeout(() => {
      func(...args);
    }, wait);
  };
}

// 检查通知是否过期
function isNotificationExpired(notification: NotificationState): boolean {
  const now = Date.now();
  const notificationAge = now - notification.notification.startTime;
  return notificationAge > NOTIFICATION_EXPIRY_TIME;
}

// 过滤有效的通知
function filterValidNotifications(notifications: NotificationState[]): NotificationState[] {
  return notifications
    .filter(notification => {
      // 过滤过期通知
      if (isNotificationExpired(notification)) {
        return false;
      }

      // 保存持久化通知和正在进行的任务通知
      if (notification.phase !== 'persistent' && notification.notification.status === 'running') {
        return true; // 保存正在运行的通知，即使不是persistent状态
      }

      if (notification.phase !== 'persistent') {
        return false;
      }
      
      // 过滤已完成的成功通知（超过3分钟）
      if (notification.notification.status === 'success') {
        const completionTime = notification.notification.lastUpdate;
        const timeSinceCompletion = Date.now() - completionTime;
        if (timeSinceCompletion > 3 * 60 * 1000) { // 3分钟
          return false;
        }
      }

      // 过滤已完成的错误通知（超过10分钟）
      if (notification.notification.status === 'error') {
        const completionTime = notification.notification.lastUpdate;
        const timeSinceCompletion = Date.now() - completionTime;
        if (timeSinceCompletion > 10 * 60 * 1000) { // 10分钟
          return false;
        }
      }
      
      return true;
    })
    .slice(0, MAX_STORED_NOTIFICATIONS); // 限制数量
}

// 保存通知到本地存储
export const saveNotificationsToStorage = debounce((notifications: NotificationState[]) => {
  try {
    const validNotifications = filterValidNotifications(notifications);
    
    const dataToStore: StoredNotificationData = {
      notifications: validNotifications,
      timestamp: Date.now(),
      version: '1.0.0'
    };
    
    localStorage.setItem(STORAGE_KEY, JSON.stringify(dataToStore));
    
    // 如果没有有效通知，清理存储
    if (validNotifications.length === 0) {
      localStorage.removeItem(STORAGE_KEY);
    }
  } catch (error) {
    console.warn('Failed to save notifications to storage:', error);
  }
}, 500); // 500ms防抖

// 从本地存储加载通知
export function loadNotificationsFromStorage(): NotificationState[] {
  try {
    const storedData = localStorage.getItem(STORAGE_KEY);
    
    if (!storedData) {
      return [];
    }
    
    const parsedData: StoredNotificationData = JSON.parse(storedData);
    
    // 检查版本兼容性
    if (!parsedData.version || parsedData.version !== '1.0.0') {
      console.warn('Incompatible notification storage version, clearing storage');
      localStorage.removeItem(STORAGE_KEY);
      return [];
    }
    
    // 检查数据是否过期（超过24小时）
    const dataAge = Date.now() - parsedData.timestamp;
    if (dataAge > NOTIFICATION_EXPIRY_TIME) {
      console.info('Stored notifications expired, clearing storage');
      localStorage.removeItem(STORAGE_KEY);
      return [];
    }
    
    // 过滤有效通知
    const validNotifications = filterValidNotifications(parsedData.notifications);

    // 修复恢复的通知状态，确保与新的Dynamic Island兼容
    const restoredNotifications = validNotifications.map(notification => {
      // 检查正在运行的通知是否需要状态修复
      if (notification.notification.status === 'running') {
        const timeSinceUpdate = Date.now() - notification.notification.lastUpdate;

        // 如果超过5分钟没有更新，标记为可能失败
        if (timeSinceUpdate > 5 * 60 * 1000) {
          return {
            ...notification,
            notification: {
              ...notification.notification,
              status: 'warning' as const,
              title: '任务状态未知',
              description: '任务可能已中断，请检查状态',
              lastUpdate: Date.now(),
            }
          };
        }
      }

      return notification;
    });

    // 日志信息
    if (restoredNotifications.length > 0) {
      console.info(`Restored ${restoredNotifications.length} notifications from storage`);
    }

    // 如果没有有效通知，清理存储
    if (restoredNotifications.length === 0) {
      localStorage.removeItem(STORAGE_KEY);
      return [];
    }

    return restoredNotifications;
  } catch (error) {
    console.warn('Failed to load notifications from storage:', error);
    // 清理损坏的存储数据
    localStorage.removeItem(STORAGE_KEY);
    return [];
  }
}

// 清理存储
export function clearNotificationStorage(): void {
  try {
    localStorage.removeItem(STORAGE_KEY);
  } catch (error) {
    console.warn('Failed to clear notification storage:', error);
  }
}

// 检查存储是否可用
export function isStorageAvailable(): boolean {
  try {
    const testKey = '__storage_test__';
    localStorage.setItem(testKey, 'test');
    localStorage.removeItem(testKey);
    return true;
  } catch {
    return false;
  }
}

// 获取存储使用情况
export function getStorageInfo(): {
  hasStoredNotifications: boolean;
  notificationCount: number;
  storageSize: number;
} {
  try {
    const storedData = localStorage.getItem(STORAGE_KEY);
    
    if (!storedData) {
      return {
        hasStoredNotifications: false,
        notificationCount: 0,
        storageSize: 0
      };
    }
    
    const parsedData: StoredNotificationData = JSON.parse(storedData);
    
    return {
      hasStoredNotifications: true,
      notificationCount: parsedData.notifications.length,
      storageSize: new Blob([storedData]).size
    };
  } catch {
    return {
      hasStoredNotifications: false,
      notificationCount: 0,
      storageSize: 0
    };
  }
}
